package com.dmxh.MQ;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/*MQ消费*/
@Component
@RocketMQMessageListener(consumerGroup = "2310", topic = "generateCode")
public class generateCode implements RocketMQListener<String> {

    @Value("${apicode.accessKeyId}")
    private String accessKeyId;

    @Value("${apicode.accessKeySecret}")
    private String accessKeySecret;

    @Value("${apicode.region}")
    private String region;

    @Value("${apicode.setEndpointOverride}")
    private String setEndpointOverride;

    @Value("${apicode.signName}")
    private String signName;

    @Value("${apicode.templateCode}")
    private String templateCode;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(String phone) {//拿到手机号开始发送
        if (!StrUtil.isEmpty(phone)) {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId("LTAI5tA4PMFDUX3uLLH5BhCC")//阿里Key
                    .accessKeySecret("VurZNJLNZtiA0ghyD5WoMd1o2CGC68")//密钥
                    .build());

            AsyncClient client = AsyncClient.builder()
                    .region(region) // Region ID    地域  杭州  北京
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride(setEndpointOverride))
                    .build();

            //生成验证码
            String s = RandomUtil.randomNumbers(6);
            JSONObject json = new JSONObject();
            json.put("code", s);
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(signName)          //签名
                    .templateCode(templateCode)  //模板名称
                    .phoneNumbers(phone)         //要发消息至 - 手机号
                    .templateParam(json.toJSONString())//将生成的验证码放入缓存    由于格式  所以需要转换
                    .build();

            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = null;
            try {
                resp = response.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(new Gson().toJson(resp));

//
//        /*将验证码放入缓存  并且设置超时间   一般是一分钟后失效*/
        stringRedisTemplate.opsForValue().set(phone,s);/*手机号码 的 验证码*/
        stringRedisTemplate.boundValueOps(phone).expire(10, TimeUnit.MINUTES);/*30分钟失效    MINUTES:分钟   expire:失效*/

            // Finally, close the client
            client.close();
            System.out.println("生成验证码OK");
        }
        System.out.println("消费时手机号为空 - MQ消费");
    }
}
